using System;
using System.Collections;
using System.Collections.Generic;
using BehaviorDesigner.Runtime.Tasks;
using UnityEngine;
using BehaviorDesigner.Runtime;
using UnityEngine.Rendering.Universal;

public class FixLight : EnemyAction
{
    private Vector3 targetPos;
    private float fixTime;

    private Vector2 faceDir;
    private bool getTarget;

    private PolygonCollider2D coll => GetComponent<PolygonCollider2D>();

    public override void OnStart()
    {
        targetPos = _find.curLight.GetComponent<LightControl>().lightSwitch.gameObject.transform.position;
        faceDir = (targetPos - transform.position).normalized;
        transform.localScale = new Vector3(faceDir.x > 0 ? 1 : -1, 1, 1);
        fixTime = Settings.fixTime;
        getTarget = false;
    }

    public override TaskStatus OnUpdate()
    {
        if (Math.Abs(transform.position.x - targetPos.x) <= 0.1f)
        {
            if (fixTime <= 0)
            {
                _find.curLight.gameObject.tag = "Light";
                _find.curLight.GetComponent<Light2D>().enabled = true;
                _find.findLight = false;
                return TaskStatus.Success;
            }
            getTarget = true;
            rb.velocity = Vector2.zero;
            fixTime -= Time.deltaTime;
            coll.enabled = false;
        }

        return TaskStatus.Running;
    }

    public override void OnFixedUpdate()
    {
        if(!getTarget)
            Move();
    }

    public override void OnEnd()
    {
        coll.enabled = true;
    }

    private void Move()
    {
        rb.velocity = new Vector2(faceDir.x * Settings.protalSpeed * Time.deltaTime, rb.velocity.y);
    }
}
